import Taro from "@tarojs/taro";
import { useUserStore } from "@/stores/userStore";

// 埋点事件类型
export const TRACKING_EVENTS = {
  // 页面访问
  PAGE_VIEW: "page_view",
  // 用户行为
  CLICK: "click",
  FORM_SUBMIT: "form_submit",
  // 性能监控
  PERFORMANCE: "performance",
  // 错误监控
  ERROR: "error",
  // 用户信息
  USER_INFO: "user_info",
};

// 埋点数据存储
let trackingData = {
  sessionId: "", // 会话ID
  deviceInfo: {}, // 设备信息
  userInfo: {}, // 用户信息
  pageInfo: {}, // 页面信息
  timestamp: 0, // 时间戳
};

// 初始化埋点服务
export const initTracking = async () => {
  // 生成会话ID
  trackingData.sessionId = generateSessionId();
  // 获取设备信息
  trackingData.deviceInfo = await getDeviceInfo();
  // 获取用户信息
  const userStore = useUserStore();
  trackingData.userInfo = userStore.getUserInfo;
  // 设置时间戳
  trackingData.timestamp = Date.now();
};

// 生成会话ID
const generateSessionId = () => {
  return (
    "session_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9)
  );
};

// 获取设备信息
const getDeviceInfo = async () => {
  try {
    const systemInfo = await Taro.getSystemInfo();
    return {
      platform: systemInfo.platform,
      model: systemInfo.model,
      system: systemInfo.system,
      version: systemInfo.version,
      screenWidth: systemInfo.screenWidth,
      screenHeight: systemInfo.screenHeight,
      pixelRatio: systemInfo.pixelRatio,
      language: systemInfo.language,
      windowWidth: systemInfo.windowWidth,
      windowHeight: systemInfo.windowHeight,
    };
  } catch (error) {
    console.error("获取设备信息失败:", error);
    return {};
  }
};

// 基础埋点方法
export const track = (eventType, eventData = {}) => {
  const trackingEvent = {
    eventType,
    ...trackingData,
    ...eventData,
    timestamp: Date.now(),
  };

  // 发送埋点数据
  sendTrackingData(trackingEvent);
};

// 发送埋点数据
const sendTrackingData = (data) => {
  // 这里可以添加实际的发送逻辑，比如调用后端API
  console.log("埋点数据:", data);

  // 示例：发送到后端
  // Taro.request({
  //   url: 'YOUR_TRACKING_API',
  //   method: 'POST',
  //   data: data
  // })
};

// 页面访问埋点
export const trackPageView = (pagePath, pageTitle) => {
  track(TRACKING_EVENTS.PAGE_VIEW, {
    pagePath,
    pageTitle,
    referrer:
      Taro.getCurrentPages().length > 1
        ? Taro.getCurrentPages()[Taro.getCurrentPages().length - 2].route
        : "",
  });
};

// 用户行为埋点
export const trackClick = (elementId, elementName, extraData = {}) => {
  track(TRACKING_EVENTS.CLICK, {
    elementId,
    elementName,
    ...extraData,
  });
};

// 表单提交埋点
export const trackFormSubmit = (formId, formName, formData = {}) => {
  track(TRACKING_EVENTS.FORM_SUBMIT, {
    formId,
    formName,
    formData,
  });
};

// 性能监控埋点
export const trackPerformance = (performanceData) => {
  track(TRACKING_EVENTS.PERFORMANCE, performanceData);
};

// 错误监控埋点
export const trackError = (error) => {
  track(TRACKING_EVENTS.ERROR, {
    errorMessage: error.message,
    errorStack: error.stack,
    errorType: error.type || "unknown",
  });
};

// 用户信息更新埋点
export const trackUserInfo = (userInfo) => {
  track(TRACKING_EVENTS.USER_INFO, {
    userInfo,
  });
};
